﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


class Reader
{
    public string trainimage = UnityEngine.Application.streamingAssetsPath + @"\train-images-idx3-ubyte\train-images.bin";
    public string trainlabel = UnityEngine.Application.streamingAssetsPath + @"\train-labels-idx1-ubyte\train-labels.bin";

    public string testimage = UnityEngine.Application.streamingAssetsPath + @"\t10k-images-idx3-ubyte\t10k-images.bin";
    public string testlabel = UnityEngine.Application.streamingAssetsPath + @"\t10k-labels-idx1-ubyte\t10k-labels.bin";

    public List<byte[]> LoadImage(string filename, ref int width, ref int height)
    {
        System.IO.BinaryReader br = new System.IO.BinaryReader(System.IO.File.Open(filename, System.IO.FileMode.Open));
        br.ReadInt32();
        int count = ReadInt(br);
        width = ReadInt(br);
        height = ReadInt(br);
        List<byte[]> images = new List<byte[]>();

        for (int i = 0; i < count; i++)
        {
            byte[] oneimage = new byte[width * height];
            for (int m = 0; m < width; m++)
            {
                for (int n = 0; n < height; n++)
                {
                    oneimage[m *width + n] = br.ReadByte();
                }
            }
            images.Add(oneimage);
        }
        br.Close();
        return images;
    }


    public List<byte[]> LoadLabel(string filename)
    {
        System.IO.BinaryReader br2 = new System.IO.BinaryReader(System.IO.File.Open(filename, System.IO.FileMode.Open));
        List<byte[]> labels = new List<byte[]>();
        br2.ReadInt32();
        int itemcount = ReadInt(br2);
        for (int i = 0; i < itemcount; i++)
        {
            byte itemvalue = br2.ReadByte();
            byte[] itemvector = new byte[10];
            for (int j = 0; j < 10; j++)
            {
                itemvector[j] = 0;
            }
            itemvector[itemvalue] = 1;
            labels.Add(itemvector);
        }
        br2.Close();
        return labels;
    }

    static int ReadInt(System.IO.BinaryReader br)
    {
        int a = br.ReadByte();
        int b = br.ReadByte();
        int c = br.ReadByte();
        int d = br.ReadByte();
        return a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
    }
}
